package com.rd.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rd.dto.Result;
import com.rd.entity.ShopType;
import com.rd.mapper.ShopTypeMapper;
import com.rd.service.ShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ShopTypeServiceImpl  extends ServiceImpl<ShopTypeMapper, ShopType> implements ShopTypeService {


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String key = "cache:list";
        // 查询缓存
        String jsonList = stringRedisTemplate.opsForValue().get(key);
        if (jsonList != null) {
            // 将json转换成list
            List<ShopType> shopTypes = JSONUtil.toList(jsonList, ShopType.class);
            if (shopTypes != null){
                return Result.ok(shopTypes);
            }
        }
        // 查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        if (typeList.isEmpty()){
            return Result.fail("店铺类型不存在");
        }
        //json形式保存缓存到redis并设置过期时间
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(typeList),10, TimeUnit.MINUTES);
        return Result.ok(typeList);
    }
}
